
import { Popup, ScrollView, TextBox } from 'devextreme-react';
import React, { useImperativeHandle, useMemo, useRef, useState } from 'react';
import { intl } from "@/utils";
import { getCpasAllTids, getCpasByCategory, saveCpasDescList } from '../service';
import { useModel } from 'umi';
import notify from 'devextreme/ui/notify';
import './index.less';
import Form, { Item } from 'devextreme-react/form';


const SettingFormPupop = React.forwardRef((props: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const [visible, setVisible] = useState<boolean>(false);
    const cpasTableObj = useRef<any>({}); // tid
    const cpasTableOrigin = useRef<any>(''); // 来源
    const tempSignDataArr = [
        {
            signID: 1,
            signName: '',
        },
        {
            signID: 2,
            signName: '',
        }, {
            signID: 3,
            signName: '',
        }];

    // const [fullName, setFullName] = useState<any>("");

    const [formAllData, setFormAllData] = useState<any>({ fullName: "", isColumnNum: false });
    const refsForm = useRef<any>(null);

    const [headerTitleName, setHeaderTitleName] = useState<any>("");
    const [headerTitleRightName, setHeaderTitleRightName] = useState<any>("");
    const [headerTitleLeftName, setHeaderTitleLeftName] = useState<any>("");
    const [popupDevData, setPopupDevData] = useState<any>([]);
    const cpasFun = useRef<any>(null); // tid
    const validationRules = {
        fullName: [
            { type: 'required', message: '必填项不可删除' }
        ],
    }

    const getCpasSettingData = async (tempTid: string) => {

        const resHeader = await getCpasByCategory({
            dbname,
            tid: [tempTid],
            category: "fsHeader",
        });
        const resSign = await getCpasByCategory({
            dbname,
            tid: [tempTid],
            category: "signRow",
        });
        const resAlias = await getCpasByCategory({
            dbname,
            tid: [tempTid],
            category: "aliasName",
        });


        console.log(resHeader.data, resAlias.data, resSign.data, '@@@');

        let tempHeader: any = {};
        let tempSign: any = [];
        let tempalias: any = {};
        if (resHeader.data.length) {
            tempHeader = JSON.parse(resHeader.data[0].describe);
            setHeaderTitleLeftName(tempHeader?.headerTitleLeftText ?? '');
            setHeaderTitleRightName(tempHeader?.headerTitleRightText ?? '');
        } else {
            setHeaderTitleLeftName('');
            setHeaderTitleRightName('');
        }
        if (resAlias.data.length) {
            tempalias = JSON.parse(resAlias.data[0].describe);
            console.log(tempalias?.sheetName, tempalias, '@@@');
            setFormAllData({ fullName: tempalias?.sheetName ?? '', isColumnNum: tempalias?.isColumnNum ?? false });
            setHeaderTitleName(tempalias?.headerTitleText ?? cpasTableObj.current.capsTitleName);
        } else {
            setFormAllData({ fullName: '', isColumnNum: false });
            setHeaderTitleName(cpasTableObj.current.capsTitleName);
        }
        if (resSign.data.length) {
            tempSign = JSON.parse(resSign.data[0].describe);
            setPopupDevData(tempSign);
        } else {
            setPopupDevData(tempSignDataArr);

        }



    }

    // 自定义方法
    useImperativeHandle(ref, () => ({
        showPupop: async (curCpasObj: any, pupopFun: any) => {
            cpasFun.current = pupopFun;
            cpasTableObj.current = curCpasObj;
            cpasTableOrigin.current = `${curCpasObj.capsOrigin}-`;
            await getCpasSettingData(curCpasObj.capsTid);
            setVisible(true);
        },
    }));


    const changeData = (str: string, index: number) => {
        setPopupDevData((oldData: any) => {
            const newData = [...oldData];
            newData.forEach((item: any, itemX: number) => {
                if (itemX === index) {
                    item.signName = str;
                }
            });
            return newData;
        })

    }


    const onCancel = (isOK: boolean = false) => {
        setVisible(false);
        setFormAllData({ fullName: '', isColumnNum: false });
        setHeaderTitleName('');
        setHeaderTitleRightName('');
        setHeaderTitleLeftName('');
        setPopupDevData([]);
        cpasTableObj.current = {};
        cpasFun.current?.cancelCallback();
        if (isOK) {
            cpasFun.current?.okCallback();
        }
    }

    const getallTidsList = async () => {
        const res = await getCpasAllTids({
            dbname,
            originTableName: cpasTableOrigin.current,
            isAllTid: true
        });
        // console.log(res, '@@@ CpasAllTids');
        if (res.success) {
            const resMap = res.data.map((item: any) => item?.tid).filter((item: any) => item);
            return {
                resTid: resMap,
                resData: res.data
            };
        } else {
            notify("获取AllTids列表失败!", "error", 2000);
        }
        return {
            resTid: [],
            resData: []
        };
    }


    const onOk = async (isSaveAll: boolean) => {

        if (refsForm.current) {
            const devForm: Form = refsForm.current as Form;
            const result: any = devForm.instance.validate();
            console.log(!result.isValid, '@@@ 返回具体的结果');
            if (!result.isValid) return;
        }


        let signRowData: any = [];
        let fsHeaderData: any = [];
        let aliasNameData: any = [];
        if (isSaveAll) {
            const allTidData = await getallTidsList();
            if (allTidData.resTid.length) {
                signRowData = allTidData.resTid.map((item: any) => {
                    return {
                        tid: item,
                        category: "signRow",
                        describe: JSON.stringify(popupDevData)
                    }
                });
                fsHeaderData = allTidData.resTid.map((item: any) => {
                    return {
                        tid: item,
                        category: "fsHeader",
                        describe: JSON.stringify({ headerTitleRightText: headerTitleRightName, headerTitleLeftText: headerTitleLeftName })
                    }
                });
                aliasNameData = [{
                    tid: cpasTableObj.current.capsTid,
                    category: "aliasName",
                    describe: JSON.stringify({ sheetName: formAllData.fullName, headerTitleText: headerTitleName, isColumnNum: formAllData.isColumnNum })
                }];
            } else {
                notify(`获取全部的Tid失败！`, "error", 2000);
                // setVisiblePopup(false);
                return;
            }
        } else {
            signRowData = [{
                tid: cpasTableObj.current.capsTid,
                category: "signRow",
                describe: JSON.stringify(popupDevData)
            }];

            fsHeaderData = [{
                tid: cpasTableObj.current.capsTid,
                category: "fsHeader",
                describe: JSON.stringify({ headerTitleRightText: headerTitleRightName, headerTitleLeftText: headerTitleLeftName })
            }];
            aliasNameData = [{
                tid: cpasTableObj.current.capsTid,
                category: "aliasName",
                describe: JSON.stringify({ sheetName: formAllData.fullName, headerTitleText: headerTitleName, isColumnNum: formAllData.isColumnNum })
            }];
        }
        const signRowCpasDesc = {
            dbname,
            cpasDesc: signRowData
        }
        const fsHeaderCpasDesc = {
            dbname,
            cpasDesc: fsHeaderData
        }
        const aliasNameCpasDesc = {
            dbname,
            cpasDesc: aliasNameData
        }
        await saveCpasDescList(aliasNameCpasDesc);
        await saveCpasDescList(fsHeaderCpasDesc);
        const res = await saveCpasDescList(signRowCpasDesc);
        if (res.success) {
            notify(`导出设置修改成功！`, "success", 2000);
            onCancel(true);
        } else {
            notify(`导出设置修改失败！`, "error", 2000);
        }
    }



    return (
        <>
            <Popup
                visible={visible}
                title={`导出设计（${cpasTableObj.current.capsTabName}）`}
                width={900}
                height={460}
                onHiding={() => {
                    onCancel()
                }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk(false)
                        },
                    },

                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: '应用全部',
                            type: 'default',
                            onClick: () => onOk(true),
                        },
                    },

                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },


                ]}
            >
                <div className='settingForm'>
                    <div style={{ paddingBottom: '8px', borderBottom: "1px solid #ddd" }}>
                        <div className='settingTitle'>标题行设计</div>
                        <div className='settingbiaoti settingNoneBorder'>
                            {
                                useMemo(() => {
                                    return <TextBox value={headerTitleName}
                                        defaultValue=""
                                        width={300}
                                        height={32}
                                        placeholder='点击编辑内容'
                                        valueChangeEvent="keyup"
                                        onValueChanged={(e: any) => {
                                            const { value } = e;
                                            setHeaderTitleName(value);
                                        }}
                                    />
                                }, [headerTitleName])
                            }
                            <div style={{ fontSize: '12px', color: "#929292", textAlign: 'center' }}>{cpasTableObj.current.capsTitleDate}</div>
                        </div>
                        <div className='settingTanx settingNoneBorder'>
                            {
                                useMemo(() => {
                                    return <div className='settingTanxCenter settingTextLeft'>
                                        <TextBox value={headerTitleLeftName}
                                            defaultValue=""
                                            width={230}
                                            height={32}
                                            placeholder='点击编辑内容'
                                            valueChangeEvent="keyup"
                                            onValueChanged={(e: any) => {
                                                const { value } = e;
                                                setHeaderTitleLeftName(value);
                                            }}
                                        />
                                    </div>
                                }, [headerTitleLeftName])
                            }
                            <div className='settingTextRight'>
                                {
                                    useMemo(() => {
                                        return <TextBox value={headerTitleRightName}
                                            defaultValue=""
                                            width={230}
                                            height={32}
                                            placeholder='点击编辑内容'
                                            valueChangeEvent="keyup"
                                            onValueChanged={(e: any) => {
                                                const { value } = e;
                                                setHeaderTitleRightName(value);
                                            }}
                                        />
                                    }, [headerTitleRightName])
                                }
                            </div>
                        </div>
                    </div>
                    <div style={{ paddingBottom: '8px', borderBottom: "1px solid #ddd" }}>
                        <div className='settingTitle'>签字行设计</div>
                        <ScrollView width='100%' height='64px'>
                            <div className='settingTanx settingText settingFlex settingNoneBorder' style={{ flexWrap: 'wrap' }}>
                                {
                                    useMemo(() => {
                                        return popupDevData.map((item: any, index: number) => {
                                            return <div className='settingTanxCenter settingTextLeft' key={index}>
                                                <TextBox width={230} height={32}
                                                    //  valueChangeEvent="keyup"
                                                    defaultValue=""
                                                    value={item.signName}
                                                    placeholder='点击编辑内容'
                                                    valueChangeEvent="keyup"
                                                    onValueChanged={(e: any) => {
                                                        const { value } = e;
                                                        changeData(value, index);
                                                    }}
                                                />
                                            </div>
                                        })

                                    }, [popupDevData])
                                }
                            </div>
                        </ScrollView>
                    </div>
                    <div>
                        <div className='settingTitle'>其他设计</div>
                        <div >
                            {/* <div style={{ color: 'red', margin: '0 8px' }}>
                                *
                            </div> */}
                            <Form
                                ref={refsForm}
                                formData={formAllData}
                                colCount={2}
                                // labelMode={"hidden"}
                                // focusStateEnabled={true}
                                showColonAfterLabel={true}
                                alignItemLabels={true}
                            >
                                <Item dataField="fullName"
                                    cssClass='fullNameText'
                                    // 
                                    label={{ text: 'Sheet名称' }}
                                    validationRules={validationRules.fullName}
                                    editorOptions={{
                                        maxLength: 100,
                                        placeholder: '点击编辑内容'
                                    }} />

                                <Item
                                    dataField="isColumnNum"
                                    editorType="dxCheckBox"
                                    label={{ text: '是否配置栏次' }}
                                />
                            </Form>

                        </div>
                    </div>
                </div>
            </Popup>
        </>
    );
});

export default SettingFormPupop;
